import React, { useState, useEffect } from "react";
import {
  Card,
  Row,
  Col,
  Statistic,
  List,
  Tag,
  Typography,
  Space,
  Spin,
  message,
  Alert,
  Badge,
  Button,
  Tooltip,
  Popconfirm,
} from "antd";
import {
  TeamOutlined,
  BookOutlined,
  MessageOutlined,
  BellOutlined,
  ClockCircleOutlined,
  FileTextOutlined,
  UserOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import { adminAPI } from "../../../services/api";
import type { Activity, Announcement } from "../../../types/admin";

const { Text } = Typography;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

interface DashboardStats {
  totalTeachers: number;
  totalStudents: number;
  totalCourses: number;
  totalDiscussions: number;
}

const AdminHome: React.FC = () => {
  const [loading, setLoading] = useState(true);
  const [statsLoading, setStatsLoading] = useState(true);
  const [stats, setStats] = useState<DashboardStats>({
    totalTeachers: 0,
    totalStudents: 0,
    totalCourses: 0,
    totalDiscussions: 0,
  });
  const [activities, setActivities] = useState<Activity[]>([]);
  const [announcements, setAnnouncements] = useState<Announcement[]>([]);

  // 假数据状态
  const [mockMessages, setMockMessages] = useState([
    {
      id: 1,
      title: "李明轩：请查收本周作业反馈！",
      time: "2024-07-01 09:30",
      unread: true,
    },
    {
      id: 2,
      title: "王雨涵：下周有课程调整通知",
      time: "2024-06-30 17:20",
      unread: false,
    },
    {
      id: 3,
      title: "张浩然：新课程《人工智能导论》已上线",
      time: "2024-06-29 15:10",
      unread: true,
    },
    {
      id: 4,
      title: "系统消息：您的密码已修改成功",
      time: "2024-06-28 08:00",
      unread: false,
    },
    {
      id: 5,
      title: "AI助教：本周有3门课程有新作业发布",
      time: "2024-06-27 19:45",
      unread: true,
    },
  ]);
  const [mockNotifications, setMockNotifications] = useState([
    {
      id: 1,
      title: "系统维护通知",
      content: "平台将于本周日凌晨2点维护，预计持续2小时。",
      time: "2024-06-29 12:00",
      unread: true,
    },
    {
      id: 2,
      title: "新功能发布",
      content: "AI助教功能已上线，欢迎体验！",
      time: "2024-06-28 10:00",
      unread: false,
    },
    {
      id: 3,
      title: "课程变更提醒",
      content: "《数据结构》课程时间调整为每周三上午。",
      time: "2024-06-27 16:30",
      unread: true,
    },
    {
      id: 4,
      title: "考试提醒",
      content: "《操作系统》期末考试将于7月10日举行。",
      time: "2024-06-26 09:00",
      unread: false,
    },
    {
      id: 5,
      title: "安全提示",
      content: "请勿泄露账号密码，定期修改密码保障安全。",
      time: "2024-06-25 14:20",
      unread: true,
    },
  ]);

  // 获取统计数据
  const fetchStats = async () => {
    try {
      console.log("📊 获取管理员统计数据...");
      
      // 使用写死的数据，不调用API
      await new Promise((resolve) => setTimeout(resolve, 300)); // 模拟加载延迟

        setStats({
        totalTeachers: 20,
        totalStudents: 789,
        totalCourses: 45,
        totalDiscussions: 56,
        });
    } catch (error) {
      console.error("❌ 获取统计数据失败:", error);
      message.error("获取统计数据失败");

      // 设置默认值
      setStats({
        totalTeachers: 20,
        totalStudents: 789,
        totalCourses: 45,
        totalDiscussions: 56,
      });
    } finally {
      setStatsLoading(false);
    }
  };

  // 获取最近活动
  const fetchActivities = async () => {
    try {
      console.log("🔄 获取最近活动...");
      
      // 使用写死的数据，不调用API
      await new Promise((resolve) => setTimeout(resolve, 200)); // 模拟加载延迟

      const mockActivities: Activity[] = [
        {
          id: "1",
          type: "course",
          title: "新课程已创建",
          content: "教师李教授创建了新课程《人工智能导论》",
          createTime: "2024-01-20 14:30:00",
          user: {
            id: "t1",
            name: "李教授",
            role: "teacher",
          },
        },
        {
          id: "2",
          type: "exam",
          title: "考试已发布",
          content: "《高等数学(一)》期末考试已发布",
          createTime: "2024-01-20 10:15:00",
          user: {
            id: "t2",
            name: "王教授",
            role: "teacher",
          },
        },
        {
          id: "3",
          type: "discussion",
          title: "新讨论已创建",
          content: "学生张明华创建了讨论《高等数学学习方法分享》",
          createTime: "2024-01-19 16:45:00",
          user: {
            id: "s1",
            name: "张明华",
            role: "student",
          },
        },
        {
          id: "4",
          type: "system",
          title: "系统更新完成",
          content: "教学平台v2.1更新已成功部署，新功能已上线",
          createTime: "2024-01-19 08:30:00",
        },
        {
          id: "5",
          type: "course",
          title: "课程信息更新",
          content: "《数据结构与算法》课程信息已更新",
          createTime: "2024-01-18 14:20:00",
          user: {
            id: "t5",
            name: "陈副教授",
            role: "teacher",
          },
        },
      ];

      setActivities(mockActivities);
    } catch (error) {
      console.error("❌ 获取活动数据失败:", error);
      setActivities([]);
    }
  };

  // 获取公告
  const fetchAnnouncements = async () => {
    try {
      console.log("📢 获取系统公告...");
      
      // 使用写死的数据，不调用API
      await new Promise((resolve) => setTimeout(resolve, 200)); // 模拟加载延迟

      const mockAnnouncements: Announcement[] = [
        {
          id: "1",
          title: "系统维护通知",
          content: "系统将于本周日凌晨2点进行例行维护，预计持续2小时，期间可能影响部分功能使用",
          createTime: "2024-01-20",
          priority: "high",
          status: "active",
        },
        {
          id: "2",
          title: "新功能发布通知",
          content: "系统新增AI助教功能，支持智能问答、作业批改等功能，欢迎师生使用体验",
          createTime: "2024-01-19",
          priority: "medium",
          status: "active",
        },
        {
          id: "3",
          title: "期末考试安排",
          content: "2024年秋季学期期末考试将于12月20日开始，请各位同学做好准备",
          createTime: "2024-01-18",
          priority: "high",
          status: "active",
        },
        {
          id: "4",
          title: "教师培训通知",
          content: "新功能使用培训将于本周五下午2点在会议室A举行，请相关教师参加",
          createTime: "2024-01-17",
          priority: "low",
          status: "active",
        },
      ];

      setAnnouncements(mockAnnouncements);
    } catch (error) {
      console.error("❌ 获取公告数据失败:", error);
      setAnnouncements([]);
    }
  };

  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      await Promise.all([
        fetchStats(),
        fetchActivities(),
        fetchAnnouncements(),
      ]);
      setLoading(false);
    };

    loadData();
  }, []);

  const getActivityIcon = (type: Activity["type"]) => {
    switch (type) {
      case "course":
        return <BookOutlined />;
      case "exam":
        return <FileTextOutlined />;
      case "discussion":
        return <MessageOutlined />;
      case "system":
        return <BellOutlined />;
      default:
        return <ClockCircleOutlined />;
    }
  };

  const getPriorityColor = (priority: Announcement["priority"]) => {
    switch (priority) {
      case "high":
        return "red";
      case "medium":
        return "orange";
      case "low":
        return "blue";
      default:
        return "blue";
    }
  };

  // 假交互方法
  const markMessageRead = (id: number) => {
    setMockMessages((prev) => prev.map(msg => msg.id === id ? { ...msg, unread: false } : msg));
  };
  const deleteMessage = (id: number) => {
    setMockMessages((prev) => prev.filter(msg => msg.id !== id));
  };
  const refreshMessages = () => {
    // 重新加载假数据
    setMockMessages([
      {
        id: 1,
        title: "李明轩：请查收本周作业反馈！",
        time: "2024-07-01 09:30",
        unread: true,
      },
      {
        id: 2,
        title: "王雨涵：下周有课程调整通知",
        time: "2024-06-30 17:20",
        unread: false,
      },
      {
        id: 3,
        title: "张浩然：新课程《人工智能导论》已上线",
        time: "2024-06-29 15:10",
        unread: true,
      },
      {
        id: 4,
        title: "系统消息：您的密码已修改成功",
        time: "2024-06-28 08:00",
        unread: false,
      },
      {
        id: 5,
        title: "AI助教：本周有3门课程有新作业发布",
        time: "2024-06-27 19:45",
        unread: true,
      },
    ]);
  };
  const markNotificationRead = (id: number) => {
    setMockNotifications((prev) => prev.map(n => n.id === id ? { ...n, unread: false } : n));
  };
  const deleteNotification = (id: number) => {
    setMockNotifications((prev) => prev.filter(n => n.id !== id));
  };
  const refreshNotifications = () => {
    setMockNotifications([
      {
        id: 1,
        title: "系统维护通知",
        content: "平台将于本周日凌晨2点维护，预计持续2小时。",
        time: "2024-06-29 12:00",
        unread: true,
      },
      {
        id: 2,
        title: "新功能发布",
        content: "AI助教功能已上线，欢迎体验！",
        time: "2024-06-28 10:00",
        unread: false,
      },
      {
        id: 3,
        title: "课程变更提醒",
        content: "《数据结构》课程时间调整为每周三上午。",
        time: "2024-06-27 16:30",
        unread: true,
      },
      {
        id: 4,
        title: "考试提醒",
        content: "《高等数学(一)》期末考试将于1月25日举行。",
        time: "2024-06-26 09:00",
        unread: false,
      },
      {
        id: 5,
        title: "安全提示",
        content: "请勿泄露账号密码，定期修改密码保障安全。",
        time: "2024-06-25 14:20",
        unread: true,
      },
    ]);
  };

  return (
    <div style={{ padding: "24px" }}>
      <Row gutter={24}>
        <Col span={6}>
          <StyledCard>
            <Statistic
              title="总教师数"
              value={stats.totalTeachers}
              prefix={<TeamOutlined />}
            />
          </StyledCard>
        </Col>
        <Col span={6}>
          <StyledCard>
            <Statistic
              title="总学生数"
              value={stats.totalStudents}
              prefix={<TeamOutlined />}
            />
          </StyledCard>
        </Col>
        <Col span={6}>
          <StyledCard>
            <Statistic
              title="课程总数"
              value={stats.totalCourses}
              prefix={<BookOutlined />}
            />
          </StyledCard>
        </Col>
        <Col span={6}>
          <StyledCard>
            <Statistic
              title="讨论总数"
              value={stats.totalDiscussions}
              prefix={<MessageOutlined />}
            />
          </StyledCard>
        </Col>
      </Row>

      <Row gutter={24}>
        <Col span={12}>
          <StyledCard title="最近活动">
            <List
              itemLayout="horizontal"
              dataSource={activities}
              renderItem={(activity) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={getActivityIcon(activity.type)}
                    title={
                      <Space>
                        {activity.title}
                        <Tag color="blue">{activity.type}</Tag>
                      </Space>
                    }
                    description={
                      <>
                        <div>{activity.content}</div>
                        <Text type="secondary">
                          <ClockCircleOutlined /> {activity.createTime}
                          {activity.user && (
                            <Tag color="cyan" style={{ marginLeft: 8 }}>
                              {activity.user.name}
                            </Tag>
                          )}
                        </Text>
                      </>
                    }
                  />
                </List.Item>
              )}
            />
          </StyledCard>
        </Col>
        <Col span={12}>
          <StyledCard title="系统公告">
            <List
              itemLayout="horizontal"
              dataSource={announcements}
              renderItem={(announcement) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<BellOutlined />}
                    title={
                      <Space>
                        {announcement.title}
                        <Tag color={getPriorityColor(announcement.priority)}>
                          {announcement.priority}
                        </Tag>
                      </Space>
                    }
                    description={
                      <>
                        <div>{announcement.content}</div>
                        <Text type="secondary">
                          <ClockCircleOutlined /> {announcement.createTime}
                        </Text>
                      </>
                    }
                  />
                </List.Item>
              )}
            />
          </StyledCard>
        </Col>
      </Row>

      <Row gutter={24} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <StyledCard
            title={
              <Space>
                <MessageOutlined /> 消息
                <Tooltip title="刷新">
                  <Button size="small" icon={<ReloadOutlined />} onClick={refreshMessages} />
                </Tooltip>
              </Space>
            }
          >
            {mockMessages.length === 0 ? (
              <Text type="secondary">暂无消息</Text>
            ) : (
              <List
                dataSource={mockMessages}
                renderItem={item => (
                  <List.Item
                    actions={[
                      item.unread && (
                        <Button size="small" type="link" onClick={() => markMessageRead(item.id)}>
                          标为已读
                        </Button>
                      ),
                      <Popconfirm title="确定删除该消息？" onConfirm={() => deleteMessage(item.id)} okText="删除" cancelText="取消">
                        <Button size="small" type="link" danger>
                          删除
                        </Button>
                      </Popconfirm>
                    ].filter(Boolean)}
                  >
                    <List.Item.Meta
                      avatar={<Badge dot={item.unread}><MessageOutlined style={{ fontSize: 18 }} /></Badge>}
                      title={<span style={{ fontWeight: item.unread ? 600 : 400 }}>{item.title}</span>}
                      description={<span style={{ color: '#999' }}>{item.time}</span>}
                    />
                  </List.Item>
                )}
              />
            )}
          </StyledCard>
        </Col>
        <Col span={12}>
          <StyledCard
            title={
              <Space>
                <BellOutlined /> 通知
                <Tooltip title="刷新">
                  <Button size="small" icon={<ReloadOutlined />} onClick={refreshNotifications} />
                </Tooltip>
              </Space>
            }
          >
            {mockNotifications.length === 0 ? (
              <Text type="secondary">暂无通知</Text>
            ) : (
              <List
                dataSource={mockNotifications}
                renderItem={item => (
                  <List.Item
                    actions={[
                      item.unread && (
                        <Button size="small" type="link" onClick={() => markNotificationRead(item.id)}>
                          标为已读
                        </Button>
                      ),
                      <Popconfirm title="确定删除该通知？" onConfirm={() => deleteNotification(item.id)} okText="删除" cancelText="取消">
                        <Button size="small" type="link" danger>
                          删除
                        </Button>
                      </Popconfirm>
                    ].filter(Boolean)}
                  >
                    <List.Item.Meta
                      avatar={<Badge dot={item.unread}><BellOutlined style={{ fontSize: 18 }} /></Badge>}
                      title={<span style={{ fontWeight: item.unread ? 600 : 400 }}>{item.title}</span>}
                      description={<span style={{ color: '#999' }}>{item.time} {item.content && <span style={{ marginLeft: 8, color: '#888' }}>{item.content}</span>}</span>}
                    />
                  </List.Item>
                )}
              />
            )}
          </StyledCard>
        </Col>
      </Row>
    </div>
  );
};

export default AdminHome;
